import mysql.connector
import matplotlib.pyplot as plt

# 配置MySQL数据库连接参数
config = {
    'user': 'root',       # 数据库用户名
    'password': 'kyds2333', # 数据库密码
    'host': 'localhost',  # 数据库主机地址
    'database': 'pythonfinal'  # 数据库名称
}

# 连接到MySQL数据库
conn = mysql.connector.connect(**config)
cursor = conn.cursor()

# 查询总题目数量
cursor.execute("SELECT COUNT(*) AS total_questions FROM questions")
total_questions = cursor.fetchone()[0]

# 查询每种题目类型的数量
query = """
SELECT question_type, COUNT(*) AS count
FROM questions
GROUP BY question_type
ORDER BY question_type;
"""
cursor.execute(query)
question_counts = cursor.fetchall()

# 关闭数据库连接
conn.close()

# 打印查询结果
print(f"总题目数量: {total_questions}")
for question_type, count in question_counts:
    print(f"题目类型 '{question_type}' 数量: {count}")

# 准备绘图数据
labels = [row[0] for row in question_counts]
sizes = [row[1] for row in question_counts]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0']  # 添加更多颜色以区分更多类型

# 设置Matplotlib以支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False    # 正常显示负号

# 绘制饼图
plt.figure(figsize=(8, 6))
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title(f'题库中每种题目类型的比例 (总题目数量: {total_questions})')
plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

# 显示图表
plt.show()
